package commander;

import gitobject.*;

import fileoperation.FileCopy;
import fileoperation.FileRead;
import fileoperation.FileStatus;
import repository.Repository;

import java.io.File;
/*
1、git branch：打印所有的分支，并在当前分支前标注 *
2、git branch [<branchname>]：新建一个分支，其名字为<branchname>，但是仍然保持在当前分支下
3、git branch –d [<branchname>]：删除名为<branchname>的分支
4、调用FileStatus函数判断branch 是否存在
 */
public class branch extends Command{
    //打印所有分支
    public void branch(){
        String currentBranch = FileRead.readBranchFromHead(this.head);
        File branchDir = new File(Repository.getGitDir() + File.separator + "refs/heads");
        //branchDir 为储存分支指针的文件列表，refs/heads为repository中储存所有分支指针的文件夹
        StringBuilder res = new StringBuilder();
        for(File f:branchDir.listFiles()){
            if(f.getName().equals(currentBranch.split("\\/")[2])) res.append("* ");
            //f为当前分支时，加*
            res.append(f.getName());
            res.append("\n");
        }
        System.out.println();
        System.out.println(res);
    }
    //新建branchName分支,注意创建分支时Head并不会转移到新分支上
    public void branch(String branchName) throws Exception{
        if (!FileStatus.branchExist(branchName)){
            //FileCopy.copy(new File(wrapGit(FileRead.readBranchFromHead(this.head))),new File(wrapGit("refs/heads/"+branchName)));
            new Branch (branchName,"").writeObject();
        }
        else {

          //  FileCopy.copy(new File(wrapGit(FileRead.readBranchFromHead(this.head))),new File(wrapGit("refs/heads/"+branchName)));
            // 原来分支内容拷贝进新分支
          //  new Branch(branchName,head.);
            //调用FileCopy函数在当前Commit节点上新建分支，故直以新文件名接复制此分支即可
        }

    }

    //删除branchName分支
    public void branch_d(String branchName) throws Exception{
        String currentBranch = FileRead.readBranchFromHead(this.head);
        File branchDir = new File(Repository.getGitDir() + File.separator + "refs/heads");
        File file = new File(Repository.getGitDir() + File.separator + "refs/heads" + File.separator + branchName);
        if (file.exists()){
            for(File f:branchDir.listFiles()) {
                if (f.getName().equals(branchName)) {
                    f.delete();
                }
            }
        }else{
            System.out.println(branchName + " not exists");
        }

    }

    /*
    public static void main(String[] args){
        try{
            branch b = new branch();
            if(args.length==0) b.branch();
            else b.branch(args[0]);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }*/

}
